#!/bin/bash
#
# Called from fpp_init or fpp_start to configure stuff
# needed prior to network init
#
#

BINDIR=$(cd $(dirname $0) && pwd)

. ${BINDIR}/common
. ${BINDIR}/functions

teeOutput

echo "FPP - Setting up for the Falcon Player on the ${FPPPLATFORM} platform"

grep -q "/home/fpp/media" /etc/fstab
if [ $? -eq 1 ]
then
    cat <<-EOF >> /etc/fstab
#####################################
#/dev/sda1     /home/fpp/media  auto    defaults,noatime,nodiratime,exec,nofail,flush,uid=500,gid=500  0  0
#####################################
EOF

fi


DIRS="config effects logs music playlists scripts sequences upload videos plugins plugindata exim4 images cache backups tmp"
echo "FPP - Checking for required directories"
chown ${FPPUSER}.${FPPUSER} ${FPPHOME}/media
for DIR in ${DIRS}
do
    if [ ! -d ${FPPHOME}/media/${DIR} ]
    then
        echo "      Creating ${DIR}"
        mkdir -p ${FPPHOME}/media/${DIR}
        chown ${FPPUSER}.${FPPUSER} ${FPPHOME}/media/${DIR}
    fi
done

if [ ! -f ${FPPHOME}/media/config/.htaccess ]; then
    if [ -f /etc/php-fpm.conf -o -f /etc/php/*/fpm/php.ini ]; then
        # FPP PHP settings are in /opt/fpp/www/.user.ini when using php-fpm
        echo > ${FPPHOME}/media/config/.htaccess
    else
        # FPP PHP settings are in .htaccess when using mod_php.  If updating
        # this string of PHP options, also update /opt/fpp/www/.user.ini for php-fpm
        # and /opt/fpp/www/common/settings.php which rewrites .htaccess.
        echo "php_value max_input_vars 5000" > ${FPPHOME}/media/config/.htaccess
        echo "php_value upload_max_filesize 4G" >> ${FPPHOME}/media/config/.htaccess
        echo "php_value post_max_size 4G" >> ${FPPHOME}/media/config/.htaccess
        echo "SetEnvIf Host ^ LOCAL_PROTECT=0" >> ${FPPHOME}/media/config/.htaccess
    fi
fi

# Create an empty .htpasswd
if [ ! -f ${FPPHOME}/media/config/.htpasswd ]; then
  echo > ${FPPHOME}/media/config/.htpasswd
fi

# Fixup ownership when mounted on an non-FAT filesystem
chown -R ${FPPUSER}.${FPPUSER} ${FPPHOME}/media

# need to make samba log dir or samba may not start
mkdir -p /var/log/samba

BOOTACTIONS=$(getSetting BootActions)
if [ "x${BOOTACTIONS}" != "x" ]; then
    /opt/fpp/scripts/handle_boot_actions
fi

# Configure Network and DNS
#echo "FPP - Configuring Network"
SKIPNETWORKRESET=$(getSetting SkipNetworkReset)

if [ -f /etc/fpp/desktop ]; then
    SKIPNETWORKRESET=1
fi
if [ "x${SKIPNETWORKRESET}" != "x1" ]; then
    SetupFPPNetworkConfig
fi

if [ -f "/.dockerenv" ]
then
	OURHOSTNAME=$(getSetting HostName)
	CID=$(head -1 /proc/1/cgroup | sed -e "s/.*docker-//" | cut -c1-12)

	if [ "x${OURHOSTNAME}" != "x${HOSTNAME}" -a "x${HOSTNAME}" != "x${CID}" ]
	then
		sed -i '/^HostName =/d' /home/fpp/media/settings
		echo "HostName = \"${HOSTNAME}\"" >> /home/fpp/media/settings
	fi

	OURHOSTDESC=$(getSetting HostDescription | grep -v "^Docker ID:")
	if [ "x${OURHOSTDESC}" = "x" ]
	then
		sed -i '/^HostDescription =/d' /home/fpp/media/settings
		echo "HostDescription = \"Docker ID: ${CID}\"" >> /home/fpp/media/settings
	fi
else
	HOSTNAME=$(getSetting HostName)
	if [ "x${HOSTNAME}" != "x" -a "x$(hostname)" != "x${HOSTNAME}" ]
	then
		echo "FPP - Setting hostname to ${HOSTNAME}"
		echo ${HOSTNAME} > /etc/hostname
		sed -i '/^127.0.1.1[^0-9]/d' /etc/hosts
		sed -i "\$a127.0.1.1 ${HOSTNAME}" /etc/hosts
		hostname ${HOSTNAME}
		/etc/init.d/avahi-daemon restart
	fi
fi

# Clear any restart/reboot flags
echo "FPP - Clearing reboot flags"
sed -i -e "s/^rebootFlag .*/rebootFlag = 0/" ${FPPHOME}/media/settings

if [ ! -f /etc/fpp/desktop ]; then
# make sure the media directory in the settings matches what we used at boot
echo "FPP - Sanity checking storage device setting"
MEDIADEV=`findmnt -n -o SOURCE /home/fpp/media | colrm 1 5`
if [ "$MEDIADEV" = "" ]; then
    MEDIADEV=`findmnt -n -o SOURCE / | colrm 1 5`
fi
if grep -q storageDevice "${FPPHOME}/media/settings"; then
    sed -i -e "s#^storageDevice .*#storageDevice = \"$MEDIADEV\"#" ${FPPHOME}/media/settings
else
    echo "storageDevice = \"$MEDIADEV\"" >> ${FPPHOME}/media/settings
fi

LASTBLOCK=$(sfdisk -q -l -o sectors /dev/mmcblk0 2>/dev/null | tail -n 1)
if [ "$LASTBLOCK" == "" ]; then 
    LASTBLOCK=0
fi
setSetting LastBlock $LASTBLOCK
fi

echo "FPP - Setting max IGMP memberships"
sysctl net/ipv4/igmp_max_memberships=512 > /dev/null 2>&1


if [ "${FPPPLATFORM}" = "BeagleBone Black" ]
then
    # need to disable the slower idle state as it takes 130ns to get 
    # out of that state which can disrupt the ws2811 timing enough
    # to get extra strobing
    if [[ -f /usr/bin/cpupower ]]; then
        cpupower idle-set -d 1
    fi
    # Also need to use the performance governor or USB is very slow
    if [[ -f /sys/devices/system/cpu/cpufreq/policy0/scaling_governor ]]; then
        echo "GOVERNOR=\"performance\"" > /etc/default/cpufrequtils
        cpufreq-set -g performance
    fi

    if [ "${BBBMODEL}" != "PocketBeagle" ]; then
        uboot=$(dd if=/dev/mmcblk1 count=23 skip=393248 bs=1 2>/dev/null || true)
        if [[ $uboot != *"U-Boot 2019.04-g72e2ec7"* ]]; then
            cd /opt/fpp/bin.bbb/bootloader
            dd if=MLO of=/dev/mmcblk1 seek=1 bs=128k
            dd if=u-boot.img of=/dev/mmcblk1 seek=1 bs=384k
            echo 'rebootFlag = "1"' >> /home/fpp/media/settings
        fi
    fi

    #configure the LEDS per user settings
    configureBBBLeds
fi

##############################################################################
# Leave these things till last so user can see output of anything above here
##############################################################################
if [ ! -f /etc/fpp/desktop ]; then
applyScreenBlankSetting
fi

#make sure the entire media dir and subdirs is writable by fpp user
chown -R ${FPPUSER}.${FPPUSER} ${FPPHOME}/media
